import Decimal from 'decimal.js';

/**
 * @description: 求和
 * @return {*}
 */
export const calculateAdd = (num1: number | string, num2: number | string) => new Decimal(num1).add(num2).toNumber();

/**
 * @description: 减法
 * @return {*}
 */
export const calculateSubtract = (num1: number | string, num2: number | string) => new Decimal(num1).minus(num2).toNumber();

/**
 * 乘法
 */
export const calculateMultiply = (number, timesNumber) => {
  const num1 = new Decimal(number);
  const num2 = new Decimal(timesNumber);
  return num1.times(num2).toNumber();
};

/**
 * 除法
 */
export const calculateDivide = (number, divideNumber) => {
  const num1 = new Decimal(number);
  const num2 = new Decimal(divideNumber);
  return num1.div(num2).toNumber();
};

/**
 * 保留 digit 位小数
 */
export const calculateToFixed = (number: number, digit: number = 2) => {
  const d = [0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000];
  return Math.round(number * d[digit]) / d[digit];
};

/**
 * 计算A是B的百分之多少
 */

export const calculatePercentage = (a: number, b: number) => {
  if (b === 0) {
    return 0;
  }
  return (a / b) * 100;
};

export const calculate = {
  add: calculateAdd,
  subtract: calculateSubtract,
  multiply: calculateMultiply,
  toFixed: calculateToFixed,
  calculatePercentage,
  divide: calculateDivide
};
